# encoding=utf8  
import pymysql
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import json
import string
import random
from time import strftime
from time import localtime
from time import time

#监听的服务器端口
SERVER_PORT=1234

#数据库地址
SQL_HOST='xxx.xxx.xx.xxx'
#数据库端口
SQL_PORT=3306
#数据库用户名密码
SQL_user='xxxx'
SQL_pass='xxxxxx'
#数据库的名字,必须是Hey_guys
SQL_DBname='Hey_guys'
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True
    def sendhh(self,mem):
        print('我给<%s>发送了消息:'%(self.request.remote_ip)+mem)
        self.write_message(u""+mem)

    def open(self):
        print('<%s>连接上我了'%(self.request.remote_ip))

    def on_message(self, message):
        print('接收到<%s>消息:'%(self.request.remote_ip)+message)
        message=json.loads(message)
        times_all=json.loads(message[0].replace('\'','\"'))
        if(len(message)!=6):
            self.sendhh('401;;;成员个数不足')
            self.sendhh('bye')
            return
        if(times_all[0][8]=='2'and times_all[0][9]>'1'):
            self.sendhh('402;;;每晚22点以后不接受数据')
            self.sendhh('bye')
            return
        if(len(message[1])>66):
            self.sendhh('403;;;内容不能超过66个字')
            self.sendhh('bye')
            return
        
        if(len(message[4])<8 or len(message[4])>10):
            self.sendhh('404;;;qq号请是8-10位')
            self.sendhh('bye')
            return
            
        if(int(times_all[0])<int(strftime('%Y%m%d%H%M',localtime(time()+300)))):
            self.sendhh('405;;;时间请在五分钟以后')
            self.sendhh('bye')
            return
        for i in message:
            if(len(i)==0):
                self.sendhh('407;;;请不要有空白项')
                self.sendhh('bye')
                return
        
        #错误排查完了,建立随机码,存入数据库
        suc_flag=0
        db=pymysql.connect(host=SQL_HOST,port=SQL_PORT,user=SQL_user,password=SQL_pass,db=SQL_DBname,charset='utf8')
        cursor = db.cursor()
        
        ran_code=''.join([random.choice(string.digits) for i in range(7)])
        ran_code=(ran_code if ran_code[0]!='0' else '6'+ran_code[1:])
        hn=len(times_all)
        print('hn',hn)
        for i in range(hn):
            try:
                sql='INSERT INTO wait(ran_code,user_time,context,approach,obj_type,user_num,sub_time) VALUES(\'%d\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')'%((int(ran_code),times_all[i])+tuple(message[1:]))
                cursor.execute(sql.encode('utf8'))
                db.commit()
            except Exception as e:
                print('存数据库发生了错误',e)
                db.rollback()
        db.close()
        self.sendhh('666;;;'+ran_code+';;;'+';;;'.join(message))
        self.sendhh('bye')
    def on_close(self):
        print('<%s>下线了'%(self.request.remote_ip))
  
class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', WebSocketHandler)
        ]

        settings = { "template_path": "."}
        tornado.web.Application.__init__(self, handlers, **settings)

if __name__ == '__main__':  
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(SERVER_PORT)
    tornado.ioloop.IOLoop.instance().start()